<template>
  <div class="app-container">
    <!-- 统计概览卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <div class="statistics-card">
          <div class="card-icon temperature">
            <i class="el-icon-thermometer"></i>
          </div>
          <div class="card-content">
            <div class="card-title">平均温度</div>
            <div class="card-value">{{ overview.avgTemperature }}°C</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistics-card">
          <div class="card-icon humidity">
            <i class="el-icon-heavy-rain"></i>
          </div>
          <div class="card-content">
            <div class="card-title">平均湿度</div>
            <div class="card-value">{{ overview.avgHumidity }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistics-card">
          <div class="card-icon air-quality">
            <i class="el-icon-cloudy"></i>
          </div>
          <div class="card-content">
            <div class="card-title">平均空气质量</div>
            <div class="card-value">{{ overview.avgAirQuality }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistics-card">
          <div class="card-icon abnormal">
            <i class="el-icon-warning"></i>
          </div>
          <div class="card-content">
            <div class="card-title">异常数据</div>
            <div class="card-value">{{ overview.abnormalCount }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="统计类型" prop="statisticsType">
        <el-select v-model="queryParams.statisticsType" placeholder="请选择统计类型" clearable>
          <el-option label="日统计" value="daily" />
          <el-option label="周统计" value="weekly" />
          <el-option label="月统计" value="monthly" />
          <el-option label="年统计" value="yearly" />
        </el-select>
      </el-form-item>
      <el-form-item label="统计日期" prop="statisticsDate">
        <el-date-picker
          v-model="queryParams.statisticsDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['environment:statistics:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['environment:statistics:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['environment:statistics:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['environment:statistics:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-data-line"
          size="mini"
          @click="generateStatistics"
        >生成统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>环境数据趋势</span>
            <el-button-group style="float: right;">
              <el-button size="mini" @click="changeTrendType('temperature')" :type="trendType === 'temperature' ? 'primary' : ''">温度</el-button>
              <el-button size="mini" @click="changeTrendType('humidity')" :type="trendType === 'humidity' ? 'primary' : ''">湿度</el-button>
              <el-button size="mini" @click="changeTrendType('airQuality')" :type="trendType === 'airQuality' ? 'primary' : ''">空气质量</el-button>
            </el-button-group>
          </div>
          <div ref="trendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>设备排名</span>
          </div>
          <div ref="rankingChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>舒适度分析</span>
          </div>
          <div ref="comfortChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>异常数据统计</span>
          </div>
          <div ref="abnormalChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="statisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="统计ID" align="center" prop="statisticsId" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="统计日期" align="center" prop="statisticsDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.statisticsDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="统计类型" align="center" prop="statisticsType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.statisticsType === 'daily'" type="primary">日统计</el-tag>
          <el-tag v-else-if="scope.row.statisticsType === 'weekly'" type="success">周统计</el-tag>
          <el-tag v-else-if="scope.row.statisticsType === 'monthly'" type="warning">月统计</el-tag>
          <el-tag v-else-if="scope.row.statisticsType === 'yearly'" type="info">年统计</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="平均温度" align="center" prop="avgTemperature">
        <template slot-scope="scope">
          <span>{{ scope.row.avgTemperature }}°C</span>
        </template>
      </el-table-column>
      <el-table-column label="平均湿度" align="center" prop="avgHumidity">
        <template slot-scope="scope">
          <span>{{ scope.row.avgHumidity }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="平均空气质量" align="center" prop="avgAirQuality" />
      <el-table-column label="数据量" align="center" prop="dataCount" />
      <el-table-column label="异常数据" align="center" prop="abnormalCount">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.abnormalCount > 0" type="danger">{{ scope.row.abnormalCount }}</el-tag>
          <el-tag v-else type="success">0</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['environment:statistics:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['environment:statistics:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改统计数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统计日期" prop="statisticsDate">
              <el-date-picker
                v-model="form.statisticsDate"
                type="date"
                placeholder="选择统计日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统计类型" prop="statisticsType">
              <el-select v-model="form.statisticsType" placeholder="请选择统计类型">
                <el-option label="日统计" value="daily" />
                <el-option label="周统计" value="weekly" />
                <el-option label="月统计" value="monthly" />
                <el-option label="年统计" value="yearly" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">温度统计</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="平均温度" prop="avgTemperature">
              <el-input-number v-model="form.avgTemperature" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低温度" prop="minTemperature">
              <el-input-number v-model="form.minTemperature" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高温度" prop="maxTemperature">
              <el-input-number v-model="form.maxTemperature" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">湿度统计</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="平均湿度" prop="avgHumidity">
              <el-input-number v-model="form.avgHumidity" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低湿度" prop="minHumidity">
              <el-input-number v-model="form.minHumidity" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高湿度" prop="maxHumidity">
              <el-input-number v-model="form.maxHumidity" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">空气质量统计</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="平均空气质量" prop="avgAirQuality">
              <el-input-number v-model="form.avgAirQuality" :precision="0" :step="1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低空气质量" prop="minAirQuality">
              <el-input-number v-model="form.minAirQuality" :precision="0" :step="1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高空气质量" prop="maxAirQuality">
              <el-input-number v-model="form.maxAirQuality" :precision="0" :step="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="数据量" prop="dataCount">
              <el-input-number v-model="form.dataCount" :precision="0" :step="1" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="异常数据量" prop="abnormalCount">
              <el-input-number v-model="form.abnormalCount" :precision="0" :step="1" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成统计对话框 -->
    <el-dialog title="生成统计数据" :visible.sync="generateOpen" width="600px" append-to-body>
      <el-form ref="generateForm" :model="generateForm" label-width="120px">
        <el-form-item label="统计类型" prop="statisticsType">
          <el-select v-model="generateForm.statisticsType" placeholder="请选择统计类型">
            <el-option label="日统计" value="daily" />
            <el-option label="周统计" value="weekly" />
            <el-option label="月统计" value="monthly" />
            <el-option label="年统计" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计日期" prop="statisticsDate">
          <el-date-picker
            v-model="generateForm.statisticsDate"
            type="date"
            placeholder="选择统计日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="generateForm.deviceId" placeholder="请输入设备ID，留空则统计所有设备" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGenerate">生成统计</el-button>
        <el-button @click="generateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStatistics, getStatistics, delStatistics, addStatistics, updateStatistics, exportStatistics, generateDailyStatistics, generateWeeklyStatistics, generateMonthlyStatistics, generateYearlyStatistics, getEnvironmentTrend, getEnvironmentOverview, getAbnormalDataStatistics, getDeviceRanking, getComfortAnalysis } from "@/api/environment/statistics";
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme

export default {
  name: "Statistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计数据表格数据
      statisticsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示生成统计弹出层
      generateOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        statisticsType: null,
        statisticsDate: null
      },
      // 表单参数
      form: {},
      // 生成统计表单参数
      generateForm: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        statisticsDate: [
          { required: true, message: "统计日期不能为空", trigger: "blur" }
        ],
        statisticsType: [
          { required: true, message: "统计类型不能为空", trigger: "change" }
        ]
      },
      // 图表实例
      trendChart: null,
      rankingChart: null,
      comfortChart: null,
      abnormalChart: null,
      // 趋势图类型
      trendType: 'temperature',
      // 概览数据
      overview: {
        avgTemperature: 0,
        avgHumidity: 0,
        avgAirQuality: 0,
        abnormalCount: 0
      }
    };
  },
  created() {
    this.getList();
    this.getOverview();
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      this.loadChartData();
    });
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.rankingChart) {
      this.rankingChart.dispose();
    }
    if (this.comfortChart) {
      this.comfortChart.dispose();
    }
    if (this.abnormalChart) {
      this.abnormalChart.dispose();
    }
  },
  methods: {
    /** 查询统计数据列表 */
    getList() {
      this.loading = true;
      listStatistics(this.queryParams).then(response => {
        this.statisticsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取概览数据 */
    getOverview() {
      // 构建请求参数，包含必需的startDate和endDate
      const params = {};
      
      // 如果查询参数中有日期范围，使用它；否则使用默认的最近7天
      if (this.queryParams.statisticsDate && this.queryParams.statisticsDate.length === 2) {
        params.startDate = this.queryParams.statisticsDate[0];
        params.endDate = this.queryParams.statisticsDate[1];
        params.statisticsType = this.queryParams.statisticsType || 'daily';
      } else {
        // 默认使用最近7天的数据
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        
        params.startDate = this.formatDate(startDate);
        params.endDate = this.formatDate(endDate);
        params.statisticsType = 'daily';
      }
      
      getEnvironmentOverview(params).then(response => {
        this.overview = response.data;
      });
    },
    /** 初始化图表 */
    initCharts() {
      this.trendChart = echarts.init(this.$refs.trendChart, 'macarons');
      this.rankingChart = echarts.init(this.$refs.rankingChart, 'macarons');
      this.comfortChart = echarts.init(this.$refs.comfortChart, 'macarons');
      this.abnormalChart = echarts.init(this.$refs.abnormalChart, 'macarons');
    },
    /** 加载图表数据 */
    loadChartData() {
      this.loadTrendChart();
      this.loadRankingChart();
      this.loadComfortChart();
      this.loadAbnormalChart();
    },
    /** 加载趋势图 */
    loadTrendChart() {
      const params = {
        paramType: this.trendType,
        statisticsType: 'daily'
      };
      
      // 添加必需的日期参数
      if (this.queryParams.statisticsDate && this.queryParams.statisticsDate.length === 2) {
        params.startDate = this.queryParams.statisticsDate[0];
        params.endDate = this.queryParams.statisticsDate[1];
      } else {
        // 默认使用最近7天的数据
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        
        params.startDate = this.formatDate(startDate);
        params.endDate = this.formatDate(endDate);
      }
      
      getEnvironmentTrend(params).then(response => {
        const data = response.data;
        const option = {
          title: {
            text: this.getTrendTitle(),
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: data.dates || []
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: this.getTrendTitle(),
            type: 'line',
            data: data.values || [],
            smooth: true
          }]
        };
        this.trendChart.setOption(option);
      });
    },
    /** 加载设备排名图 */
    loadRankingChart() {
      // 构建参数对象
      let params = {};
      
      // 设置默认参数
      params.paramType = 'temperature'; // 默认按温度排序
      params.statisticsType = 'daily';
      params.orderType = 'desc';
      params.limit = 10;
      
      // 如果有日期范围选择，添加日期参数
      if (this.queryParams.statisticsDate && this.queryParams.statisticsDate.length === 2) {
        params.startDate = this.formatDate(new Date(this.queryParams.statisticsDate[0]));
        params.endDate = this.formatDate(new Date(this.queryParams.statisticsDate[1]));
      } else {
        // 默认最近7天
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        params.startDate = this.formatDate(startDate);
        params.endDate = this.formatDate(endDate);
      }
      
      // 如果有统计类型选择，使用选择的类型
      if (this.queryParams.statisticsType) {
        params.statisticsType = this.queryParams.statisticsType;
      }
      
      getDeviceRanking(params).then(response => {
        const data = response.data;
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: data.deviceNames || []
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: '数据量',
            type: 'bar',
            data: data.dataCounts || []
          }]
        };
        this.rankingChart.setOption(option);
      });
    },
    /** 加载舒适度分析图 */
    loadComfortChart() {
      // 构建请求参数，包含必需的startDate和endDate
      const params = {};
      
      // 如果查询参数中有日期范围，使用它；否则使用默认的最近7天
      if (this.queryParams.statisticsDate && this.queryParams.statisticsDate.length === 2) {
        params.startDate = this.queryParams.statisticsDate[0];
        params.endDate = this.queryParams.statisticsDate[1];
      } else {
        // 默认使用最近7天的数据
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        
        params.startDate = this.formatDate(startDate);
        params.endDate = this.formatDate(endDate);
      }
      
      getComfortAnalysis(params).then(response => {
        const data = response.data;
        const option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [{
            name: '舒适度',
            type: 'pie',
            radius: '50%',
            data: [
              { value: data.comfortableCount || 0, name: '舒适' },
              { value: (data.totalRecords - data.comfortableCount) || 0, name: '不舒适' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        };
        this.comfortChart.setOption(option);
      });
    },
    /** 加载异常数据统计图 */
    loadAbnormalChart() {
      // 构建请求参数，包含必需的startDate和endDate
      const params = {};
      
      // 如果查询参数中有日期范围，使用它；否则使用默认的最近7天
      if (this.queryParams.statisticsDate && this.queryParams.statisticsDate.length === 2) {
        params.startDate = this.queryParams.statisticsDate[0];
        params.endDate = this.queryParams.statisticsDate[1];
      } else {
        // 默认使用最近7天的数据
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 7);
        
        params.startDate = this.formatDate(startDate);
        params.endDate = this.formatDate(endDate);
      }
      
      getAbnormalDataStatistics(params).then(response => {
        const data = response.data;
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['正常数据', '异常数据']
          },
          xAxis: {
            type: 'category',
            data: data.dates || []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '正常数据',
              type: 'bar',
              stack: 'total',
              data: data.normalCounts || []
            },
            {
              name: '异常数据',
              type: 'bar',
              stack: 'total',
              data: data.abnormalCounts || []
            }
          ]
        };
        this.abnormalChart.setOption(option);
      });
    },
    /** 切换趋势图类型 */
    changeTrendType(type) {
      this.trendType = type;
      this.loadTrendChart();
    },
    /** 获取趋势图标题 */
    getTrendTitle() {
      const titles = {
        temperature: '温度趋势',
        humidity: '湿度趋势',
        airQuality: '空气质量趋势'
      };
      return titles[this.trendType] || '数据趋势';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        statisticsId: null,
        deviceId: null,
        deviceName: null,
        statisticsDate: null,
        statisticsType: null,
        avgTemperature: null,
        minTemperature: null,
        maxTemperature: null,
        avgHumidity: null,
        minHumidity: null,
        maxHumidity: null,
        avgAirQuality: null,
        minAirQuality: null,
        maxAirQuality: null,
        avgPressure: null,
        minPressure: null,
        maxPressure: null,
        avgLight: null,
        minLight: null,
        maxLight: null,
        dataCount: null,
        abnormalCount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.statisticsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加统计数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const statisticsId = row.statisticsId || this.ids
      getStatistics(statisticsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改统计数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.statisticsId != null) {
            updateStatistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStatistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const statisticsIds = row.statisticsId || this.ids;
      this.$modal.confirm('是否确认删除统计数据编号为"' + statisticsIds + '"的数据项？').then(function() {
        return delStatistics(statisticsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('environment/statistics/export', {
        ...this.queryParams
      }, `statistics_${new Date().getTime()}.xlsx`)
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push({
        path: '/environment/statistics/detail',
        query: { id: row.statisticsId }
      });
    },
    /** 生成统计按钮操作 */
    generateStatistics() {
      this.generateForm = {
        statisticsType: 'daily',
        statisticsDate: null,
        deviceId: null
      };
      this.generateOpen = true;
    },
    /** 提交生成统计 */
    submitGenerate() {
      const { statisticsType, statisticsDate, deviceId } = this.generateForm;
      if (!statisticsType || !statisticsDate) {
        this.$modal.msgError("请选择统计类型和统计日期");
        return;
      }

      const params = {
        statisticsDate,
        deviceId: deviceId || null
      };

      let generateMethod;
      switch (statisticsType) {
        case 'daily':
          generateMethod = generateDailyStatistics;
          break;
        case 'weekly':
          generateMethod = generateWeeklyStatistics;
          break;
        case 'monthly':
          generateMethod = generateMonthlyStatistics;
          break;
        case 'yearly':
          generateMethod = generateYearlyStatistics;
          break;
        default:
          this.$modal.msgError("不支持的统计类型");
          return;
      }

      generateMethod(params).then(response => {
        this.$modal.msgSuccess("统计数据生成成功");
        this.generateOpen = false;
        this.getList();
        this.getOverview();
        this.loadChartData();
      });
    },
    /** 格式化日期为 yyyy-MM-dd 格式 */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.statistics-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.card-icon.temperature {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.humidity {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.air-quality {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.abnormal {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.box-card {
  margin-bottom: 20px;
}
</style>